/**
 * 所角色的登录注册等相关业务处理
 */
// 导入常用Util
import {
  api,
  util,
  forms,
  storage
} from '../util'
// 授权模块导入
import authorize from 'authorize.js'
import { profile } from 'store.js'
import {
  category,area
} from "../modules/gloab";
import {
  router
} from "../router";
import {
  config,
  account
} from "../modules/gloab";
import { alert } from '../newUtil';
var app = getApp();

const login = {
  /**
   * 登录校验
   */

  verifylogin: function (role, data, type,callback, state_callback,sms_callback) {
    var that = this;
    var bo = forms.formValidate(data);
    if (!bo) {
      return state_callback();
    }
    var data = forms.getValues(data);
    data.proprietor = app.dns.proprietor;
    data.proprietorId = app.dns.proprietorId;
    data.LoginType = type;
    //供应商登录需要新增一个ManagerIsClerk参数
    if (role=="clerk"||role=="supplier") {
      data.ManagerIsClerk = 1;
    }    
    util.post("account."+(role=="clerk"?"supplier":role)+".verify.login", data, (res)=> {
      this.handldResult(role,res,callback,state_callback,role=='store'?true:false,sms_callback);
    }, "3.1", null, false);
  },
  /*微信校验登录 */
  wxverifylogin: function (data, role, userInfo, callback, state_callback) {
    var that = this;
    var bo = forms.formValidate(data);
    if (!bo) {
      return state_callback();
    }
    var data = forms.getValues(data);
    userInfo = util.mergeJsonObject(userInfo, data);
    userInfo.ProprietorId = app.dns.proprietorId;
    userInfo.fkid = app.dns.fkId;
    userInfo.fkflag = app.dns.fkFlag;
    userInfo.fkway = app.dns.fkWay;
    wx.login({
      success: (res) => {
        userInfo["code"] = res.code;
        util.post('account.'+(role=="clerk"?"supplier":role)+'.minipro.verifylogin', userInfo, (res) => {
          this.handldResult(role,res,callback,state_callback);
        }, "3.0", null, false);
      }
    });


  },
  /**
   * 处理结果
   * @param {*} role 角色
   * @param {*} res 返回值
   * @param {*} callback 回调
   * @param {*} state_callback 状态回调
   * @param {*} smsValidate 是否验证短信（仅客户&&账号登录验证）
   * @param {*} sms_callback 短信验证回调
   */
  handldResult:function(role,res,callback,state_callback,smsValidate=false,sms_callback){
    res = res.data;
    if (res.Success == true) {
      let is_str = typeof (res.Content) == "string";
      if (is_str||res.Content.length == 1) {
        //需要验证短信
        if(smsValidate && res.Content[0].LoginSmsValidate){
          if (sms_callback != undefined && typeof(sms_callback) == "function") {
            sms_callback(res);
          }
        }else{
          this.login(role, is_str ? res.Content:res.Content[0].Token, state_callback); //模拟登陆
        }
      }else if(res.Content.DutyType!=undefined){
        // this.login(res.Content.DutyType==0?"supplier":"clerk", res.Content.DutyType==0 ? res.Content.token:res.Content.clerkToken, state_callback);
        this.login(role,res.Content.token, state_callback);
      }            
      else if (res.Content.length > 1) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res);
        }
      }
      else {
        util.tips("用户名不存在")
        state_callback();
      }
    }else if(res.Code == 4017){
      let profileStatus = Number(res.Message.split("|")[1]);
      //需要跳转到完善页面
      if(profileStatus!=-1&&profileStatus!=3){
        router.redirect({
          path:'perfect',
          params:{
            profileStatus:profileStatus,
            profileToken:res.Message.split('|')[2] 
          }
        })
      }else{
        util.tips(res.Message.split('|')[0]);
        state_callback();
      }
    } else {
      util.tips(res.Message);
      state_callback();
    }
  },
  authInfo:{},
  //保存授权信息
  saveAuthInfo: function (role, userInfo, callback, state_callback) {
    userInfo.proprietorId = app.dns.proprietorId;
    userInfo.fkid = app.dns.fkId;
    userInfo.fkflag = app.dns.fkFlag;
    userInfo.fkway = app.dns.fkWay;
    userInfo.ZoneId = app.dns.zoneId;
    userInfo.qr = storage.get("scene")||"";
    util.post('account.' + role + '.minipro.userinfo', userInfo, (res) => {
      res = res.data;
      if (res.Success == true) {
        this.authInfo=res.Content;
        callback(res.Content);
      } else {
        util.tips(res.Message);
        state_callback();
      }
    }, "3.0", null, false);
  },

  /**
   * 授权登录
   * @param {Object} page 当前所在页面对象，用于选择用户名填写弹窗组件
   */
  onAuthLoginVerify: function (role, userInfo, callback, state_callback, page) {
    var that = this;
    userInfo.proprietorId = app.dns.proprietorId;
    userInfo.fkid = app.dns.fkId;
    userInfo.fkflag = app.dns.fkFlag;
    userInfo.fkway = app.dns.fkWay;
    userInfo.ZoneId = app.dns.zoneId;
    util.post('account.' + role + '.minipro.authlogin', userInfo, (res) => {
      res = res.data || {};
      let status = res.Code || '' // 状态值203时表示当前为该手机号未填写名称登录
      let showNameEditor = false
      if (res.Success == true) {
        if (status == 203) {
          showNameEditor = true
          login.login(role, res.Content[0].Token, state_callback, page, showNameEditor); //模拟登陆
        } else {
          if (res.Content.length == 1) {
            login.login(role, res.Content[0].Token, state_callback, page, showNameEditor); //模拟登陆
          } else if (res.Content.length > 1) {
            if (callback != undefined && typeof (callback) == "function") {
              callback(res);
            }
          }
        }
      }
      // 未填写过名称
      else if (res.Code == 4016) {
        let message = res.Message || ''
        let profileStatus = 0
        let profileToken = res.Content || ''
        let alertMessage = ''
        let editUserName = null
        if (page) {
          editUserName = page.selectComponent('#editUserName')
        }
        if (editUserName) {
          editUserName.$$showComponent({
            data: {
              profileToken
            },
            success () {
              editUserName.setData({
                showComponent: false
              })
              completeUserInfo(profileStatus, profileToken, alertMessage, message, state_callback)
            },
            fail () {
              completeUserInfo(profileStatus, profileToken, alertMessage, message, state_callback)
            }
          })
        }
      }
      else if(res.Code == 4017){
        let message = res.Message || ''
        let profileStatus = Number(message.split("|")[1])
        let profileToken = message.split('|')[2]
        let alertMessage = message.split('|')[0]
        let status = res.Content // 状态值203时表示当前为该手机号未填写名称登录
        // 微信一键登录后，需要让用户填写名称
        if (page && status == 203) {
          let editUserName = page.selectComponent('#editUserName')
          // 如果需要完善资料，则只有待完善或待审核时才显示，防止用户每次都要填写
          if (editUserName && (profileStatus == 0 || profileStatus == -1)) {
            editUserName.$$showComponent({
              data: {
                profileToken
              },
              success () {
                editUserName.setData({
                  showComponent: false
                })
                completeUserInfo(profileStatus, profileToken, alertMessage, message, state_callback)
              },
              fail () {
                completeUserInfo(profileStatus, profileToken, alertMessage, message, state_callback)
              }
            })
          } else {
            completeUserInfo(profileStatus, profileToken, alertMessage, message, state_callback)
          }
        } else {
          completeUserInfo(profileStatus, profileToken, alertMessage, message, state_callback)
        }
      }
      else if(res.Code==3003){
        state_callback(false,res);
      }
      else {
        let msg=res.Message;
        if(msg.indexOf("40029")>-1||msg.indexOf("40163")>-1){
          state_callback(false,40029);
        }
        else{
          // util.tips(res.Message);
          util.alert(res.Message);
          state_callback();
        }
      }
    }, "3.1", null, false);
  },
  wxAuthLogin: function (role, callback, state_callback, content){
    var userInfo={};
    userInfo.proprietorId = app.dns.proprietorId;
    userInfo.fkid = app.dns.fkId;
    userInfo.fkflag = app.dns.fkFlag;
    userInfo.fkway = app.dns.fkWay;
    userInfo.isClickIcon = true;
    userInfo.qr=storage.get("scene")||"";
    userInfo=util.mergeJsonObject(userInfo, content);
    util.post('account.' + role + '.wx.verifylogin', userInfo, (res) => {
      res = res.data;
      if (res.Success == true) {
        if (res.Content.length == 1) {
          login.login(role, res.Content[0].Token, state_callback); //模拟登陆
        } else if (res.Content.length > 1) {
          if (callback != undefined && typeof (callback) == "function") {
            callback(res);
          }
        }
        else {
          util.tips("用户名不存在")
          state_callback();
        }
      } else {
        util.tips(res.Message);
        state_callback();
      }
    }, "3.0", null, false);
  },
  /**
   * 模拟登录
   * @param {Object} page 当前所在页面对象，用于选择用户名填写弹窗组件
   * @param {Boolean} showNameEditor 是否显示编辑名称组件，只有第一次使用手机号登录需要判断
   */
  login: function (role, token, state_callback, page, showNameEditor = false) {
    var data = {
      PassportToken: token
    };
    util.post("account."+role+".token.login", data, function(res) {
      res = res.data;
      if (res.Success == true) {
        authorize.setCookie(role, res.Content); 
        // console.log(res.Content,'-----role','role')
        app.dns.proprietorId = authorize.getEntity(role).proprietorId;
        storage.put("dns", app.dns,0);
        if (app.dns.fkId != app.dns.proprietorId&&role=="store") {
          //加载分类
          category.load(app.dns.proprietorId, app.dns.proprietor, 0);
         
        }
        if(api.addressAssignDepot){
          area.removeCacheLocation();
        }
       
        app.globalData.index.isReload = true;
        util.removeCategoryCache()
        account.get_upload_token(1,app.dns.proprietorId);
        // 用户登录，校验是否已填写用户名，未填写则弹窗填写
        if (role == 'store' && page) {
          let editUserName = page.selectComponent('#editUserName')
          let content = res.Content || {}
          let resRole = content.role || {}
          // 当第一次手机号登录，或者没有名字时，需要填写名称
          if (editUserName && (showNameEditor || !resRole.Name)) {
            editUserName.$$showComponent({
              userId: resRole.Id || '',
              success () {
                state_callback(true, token, res.virtualPath);
              },
              fail () {
                state_callback(true, token, res.virtualPath);
              }
            })
          } else {
            state_callback(true, token, res.virtualPath);
          }
        } else {
          state_callback(true, token, res.virtualPath);
        }
      }else if(res.Code == 4017){
        let message = res.Message || ''
        let profileToken = message.split('|')[2]
        let alertMessage = message.split('|')[0]
        let profileStatus = Number(message.split("|")[1])
        if (page && showNameEditor) {
          let editUserName = page.selectComponent('#editUserName')
          if (editUserName) {
            editUserName.$$showComponent({
              data: {
                profileToken
              },
              success () {
                editUserName.setData({
                  showComponent: false
                })
                completeUserInfo(profileStatus, profileToken, alertMessage, message, state_callback)
              },
              fail () {
                completeUserInfo(profileStatus, profileToken, alertMessage, message, state_callback)
              }
            })
          }
        } else {
          completeUserInfo(profileStatus, profileToken, alertMessage, message, state_callback)
        }
      } else {
        util.tips(res.Message);
        state_callback();
      }
    },"3.1");
  },
  /**
   * 验证短信
   */
  smsValidate:function(data,callback){
    util.post("info.smscode.validate",data,function(res){
      res = res.data;
      if (res.Success == true) {
        callback(res.Content);
      } else {
        util.tips(res.Message);
      }
    },"3.0",null,false);
  }
}

const register = {
  /**
   * 获得注册协议
   */
  getProtocol: function(role, callback) {
    var proprietorId = app.dns.proprietorId;
    var proprietor = app.dns.proprietor;
    var zoneId = app.dns.zoneId;
    if (proprietor == 1) {

    }else if(proprietor == app.dns.fkFlag){
      let param = {
        proprietor:proprietor,
        proprietorId:proprietorId
      }
      util.post("annex.serviceagreement.get",param,function(res){
        res = res.data;
        if (res.Success == true) {
          callback(res.Content);
        } else {
          util.tips(res.Message);
        }
      },"3.0",null,false);
    }else {
      config.getConfig(
        proprietorId,
        proprietor,
        'Roles',
        'StoreSetting',
        function(res) {
          if (res && res.Success) {
            if (callback != undefined && typeof(callback) == "function") {
              callback(res);
            }
          }
        });
    }
  },
  /**
   * 获取隐私政策
   */
  getPrivacy:function(callback){
    let param = {
      proprietor:app.dns.proprietor,
      proprietorId:app.dns.proprietorId
    }
    util.post("annex.privacyagreement.get",param,function(res){
      res = res.data;
      if (res.Success == true) {
        callback(res.Content);
      } else {
        util.tips(res.Message);
      }
    },"3.0",null,false);
  },
  /**
   * 提交注册信息
   */
  submit: function(current_role, data, pathUrl,callback) {
    var bo = forms.formValidate(data);
    if (!bo){ callback(false);return ;}
    var data = forms.getValues(data);
    data.ProprietorId = app.dns.proprietorId;
    data.Proprietor = app.dns.proprietor;
    data.ZoneId = app.dns.zoneId;
    data.qr=storage.get("scene")||"";
    util.post("account." + current_role+".register", data, function(res) {
      res = res.data;
      if (res.Success == true) {
        let profileStatus = Number(res.Content.split('|')[3]);
        //需要跳转到完善页面
        if(profileStatus!=-1&&profileStatus!=3){
          console.log(profileStatus,'----',res.Content.split('|')[4]);
          router.redirect({
            path:'perfect',
            params:{
              profileStatus:profileStatus,
              profileToken:res.Content.split('|')[4]
            }
          })
        }else{
          router.redirect({
            path: "login",
            params: {
              role: current_role,
              userName: data.Mobile,
              password: data.Password,
              type:pathUrl
            }
          });
        }
      } else {
        util.tips(res.Message);
      }
      callback(res.Success);

    }, "3.0", null, false);
  },
  /**
   * 校验用户名
   */
  validateUserName: function(role,data, callback) {
    util.post("account." + role+".mobile.isexists", data, function(res) {
      
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    },"3.0", null, false);
  },
  customizeNext:function(role,data, callback){
    util.post(role+".customer.list", data, function(res) {
      
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    },"3.0", null, false);
  },
  /**
   * 获取邀请人信息
   */
  getCardAccount:function (qr, callback) {
    var data={
      invite:qr
    }
    util.post("account.card.get", data,
    function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(true, res.Content);
        }
      } else {
        if (callback != undefined && typeof (callback) == "function") {
          callback(false, res.Message);
        }
      }
    },"3.0");
  },
  /**
   * 获取自定义表单（名称）
   */
  getCustomize:function(callback){
    util.post("core.customize.config.get", {ProprietorId:app.dns.proprietorId}, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    },"3.0", null, false);
  },
  /**
   * 获取邀请人信息
   */
  getInviteInfo:function (scene, callback) {
    var data={
      codeInvite: scene
    }
    util.post("supplier.code.invite", data,
      function (res) {
        res = res.data;
        if (res.Success) {
          if (callback != undefined && typeof (callback) == "function") {
            callback(true, res.Content);
          }
        } else {
          if (callback != undefined && typeof (callback) == "function") {
            callback(false, res.Message);
          }
        }
      },"3.1");
  }
}

const password = {
  /*校验用户名 */
  validateUserName: function(role,data, callback) {
    util.post("account."+role+".mobile.getmanager", data, function(res) {

      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    },"3.0", null, false);
  },
  /*校验密码 */
  verify: function(role,data, callback) {
    util.post("account."+role+".forget.validatecode.check", data, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.1", null, false);
  },
  /*找回密码 */
  forget: function(role,data, callback) {
    util.post("account."+role+".password.forget", data, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0", null, false);
  },
  /**
  * 修改登录密码
  */
  update_login_pwd: function (role,data) {
    var bo = forms.formValidate(data);
    if (!bo) return;

    if (!forms.compare(data.Password, data.RepPassword)) return;

    if (data.LoginPwd.value == data.Password.value) {
      util.tips("新密码与旧密码不能相同!");
      return
    };
    var codeToken = storage.get("pic_verify_code");
    if (codeToken == undefined || codeToken.length == 0) {
      util.tips("图片验证码过期");
      return false;
    }

    var entity = authorize.getEntity();
    var param = {
      Token: entity.manager.Token,
      password: data.Password.value,
      oldpassword: data.LoginPwd.value,
      VerifyCode: data.PicVerifyCode.value,
      CodeToken: codeToken
    };
    util.post("account."+role+".password.modify", param,
      function (res) {
        res = res.data;
        if (res.Success) {
          util.alert("修改密码成功", "修改密码成功", function () {
            //退出登录
            profile.loginOut();           
            //跳转到登录页面
            if (app.dns.proprietor != app.dns.fkFlag) {
              app.dns.proprietorId = 0;
            }
            app.globalData.index.isReload = true;
            util.removeCategoryCache()
            authorize.redirect(role);
          });
        } else {
          util.tips(res.Message);
        }
      }, "3.0", null, false);
  },
  /**
   * 修改支付密码
   */
  update_pay_pwd: function (role,data,callback) {
    var bo = forms.formValidate(data);
    if (!bo) return;
    if (!checkPasswordStrength(data.Password.value)) return;
    if (!forms.compare(data.Password, data.RepPassword)) return;
    var codeToken = storage.get("pic_verify_code");
    if (codeToken == undefined || codeToken.length == 0) {
      util.alert("图片验证码过期");
      return false;
    }

    var entity = authorize.getEntity();
    var param = {
      Token: entity.manager.Token,
      FKId: entity.fkId,
      oldPassword: data.OldPassword.value,
      password: data.Password.value,
      loginPassword: data.LoginPwd.value,
      VerifyCode: data.PicVerifyCode.value,
      CodeToken: codeToken
    };
    util.post("account."+role+".paypwd.modify", param,
      function (res) {
        res = res.data;
        if (res.Success) {
          if (callback != undefined && typeof (callback) == "function") {
            callback(res.Content);
          }

        } else {
          util.tips(res.Message);
        }
      }, "3.0", null, false);
  },
  /**
   * 找回支付密码
   */
  find_pay_pwd: (role,pwd, callback) => {
    var entity = authorize.getEntity();
    var param = {
      Token: entity.manager.Token,
      FKId: entity.fkId,
      FKFlag: entity.fkFlag,
      ContextString:`{"PayPassword":"${pwd}"}`
    };
    util.post("account."+role+".paypassword.update", param,
      function (res) {
        res = res.data;

        if (res.Success) {
          if (callback != undefined && typeof (callback) == "function") {
            callback(res.Content);
          }
        } else {
          util.alert(res.Content);
        }

      },"3.0", null, false);
  },
  managerList(data,callback){
    var entity = authorize.getEntity();
    var param = {
      Token: entity.manager.Token,
      FKId: entity.fkId,
      FKFlag: entity.fkFlag,
      PageIndex:data.PageIndex,
      PageSize:data.PageSize,
      Condition:"<Keyword><![CDATA[" + (data.keywords) + "]]></Keyword>"
    };
    util.post("store.manager.list", param,function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      } else {
        util.alert(res.Message);
      }
    },"3.0", null, false);
  },
  // 添加子账号
  managerAdd(data,callback){
    var entity = authorize.getEntity();
    var param = {
      Token: entity.manager.Token,
      UserName:data.UserName,
      Password:data.Password,
      Name:data.Name,
      NickName:data.NickName,
      IsValidOrder:data.IsValidOrder?1:0
    };
    util.post("store.manager.add", param,function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      } else {
        util.alert(res.Message);
      }
    },"3.0", null, false);
  },
  //子账号更新
  managerUpdate(data,callback){
    var entity = authorize.getEntity();
    var param = {
      Token: entity.manager.Token,
      Id:data.Id,
      UserName:data.UserName,
      Password:data.Password,
      Name:data.Name,
      NickName:data.NickName,
      Status:data.Status?1:0,
      IsValidOrder:data.IsValidOrder?1:0
    };
    util.post("store.manager.update", param,function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      } else {
        util.alert(res.Message);
      }
    },"3.0", null, false);
  },
}

/**
 * 需要跳转到完善页面
 * @param {*} profileStatus 状态值，判断是否需要跳转页面，0 ：待完善（需跳转完善页）* 1：待审核（需跳转完善页）* 2：审核通过，待状态开启 （需跳转完善页）
 * @param {*} profileToken 填写信息时，需要使用的token
 * @param {*} alertMessage 弹窗提示内容
 * @param {*} message 接口返回信息
 * @param {*} state_callback 请求回调方法
 */
let completeUserInfo = (profileStatus, profileToken, alertMessage, message, state_callback) => {
  if (profileStatus != -1 && profileStatus != 3) {
    router.redirect({
      path: 'perfect',
      params: {
        profileStatus: profileStatus,
        profileToken: profileToken
      }
    })
  } else {
    util.alert(alertMessage)
    state_callback()
  }
}

/**
 * 校验密码强度
 * @param {String} password 密码字符串
 * 
 * 密码不能为连续数字和全为相同数字
 */
let checkPasswordStrength = (password = '') => {
  password = password.toString()
  if (password.length < 6) {
    alert({
      content: '密码至少需要6位'
    })
    return false
  }
  let arr = password.split('')
  let isSame = true // 密码是否全为相同的数字
  let isContinuous = true // 密码是否为连续数字
  let interval = 0 // 数字的间隔
  for (let i = 0; i < arr.length; i++) {
    if (i > 0) {
      if (arr[i - 1] != arr[i]) {
        isSame = false
      }
      // 通过ASCII码判断是否为连续内容
      let i1 = arr[i].charCodeAt()
      let i2 = arr[i - 1].charCodeAt()
      if (i > 1) {
        if (interval != (i1 - i2)) {
          isContinuous = false
        }
        interval = i1 - i2
      } else {
        interval = i1 - i2
      }
    }
  }
  if (isSame) {
    alert('密码不能全为相同的数字等内容')
    return false
  }
  if (isContinuous) {
    alert('密码不能为连续的数字等内容')
    return false
  }
  return true
}

export {
  login,
  register,
  password
}